<template>
  <div>
    <el-row style="height: 50px" type="flex" align="middle" justify="space-between">
      <el-button-group>
        <!--TODO 开始上传-->
        <el-button size="medium">
          <i v-if="isUploading || isExtraUploading" class="el-icon-loading" style="color: #10a1df"></i>
          <span v-else @click="showSliceUsesialog('autoUpload')">
            启动自动上传
            <i class="el-icon-video-play" style="color: #10a1df"></i>
          </span>
        </el-button>
        <!--TODO 停止上传-->
        <el-button :disabled="!canStopUpload" @click="stopUpload" size="medium">
          <i v-if="isStopingUpload" class="el-icon-loading" style="color: #10a1df"></i>
          <span v-else>
            停止自动上传
            <i class="el-icon-video-pause" style="color: #10a1df"></i>
          </span>
        </el-button>
        <!--TODO 补传切片-->
        <el-button v-if="isShowExtraUpload" :disabled="isUploading" size="medium">
          <span v-if="isExtraUploading" @click="addFiles">继续</span>
          <span v-else @click="showSliceUsesialog('handUpload')">
            补传
            <i class="el-icon-upload" style="color: #10a1df"></i>
          </span>
        </el-button>
        <el-button size="medium" v-if="this.$store.state.user.name === 'admin'" @click="addXmlFiles">上传xml文件</el-button>
        <!--TODO 重置数据-->
        <!-- <el-button v-if="isShowResetDatabase"
                           :disabled="!canResetDatabase"
                           @click="resetDatabase"
                           size="mini">
                    <i v-if="isResetingDatabase" class="el-icon-loading"></i>
                    <span v-else>重置</span>
        </el-button>-->
      </el-button-group>
      <!--TODO 本次/上次扫描数据拼接-->
      <span style="margin: 0 50px">{{ scanPandect }}</span>
      <!--TODO 本次/上次扫描数据详情-->
      <el-button v-if="isShowBiopsyHistory" :disabled="!isWaitUploading" @click="biopsyHistoryDialogOpen"
        style="float: right" size="mini" type="primary">
        <i v-if="!isWaitUploading" class="el-icon-loading"></i>
        <span v-else>扫描详情</span>
      </el-button>
    </el-row>
    <base-table ref="biopsyTable" :data="biopsyTable.data" :header="biopsyTable.header" :operation="biopsyTable.operation"
      :pageInfo="biopsyTable.pageInfo" :selected="false" @handleClick="biopsyTableButtonClick"
      @pageJumpTo="biopsyTablePageJumpTo" @sizeChange="biopsyTableSizeChange"></base-table>

    <el-dialog :close-on-click-modal="false" title="扫描批次详情" :visible.sync="biopsyHistoryDialog.visible" width="60%">
      <el-row class="line-text">
        <el-col :span="8">
          <span class="content-text">扫描批次序号: {{ biopsyHistory.id }}</span>
        </el-col>
        <el-col :span="8">
          <span class="content-text">操作员: {{ biopsyHistory.userName }}</span>
        </el-col>
        <!--<el-col :span="8">-->
        <!--<span class="content-text">操作员工号：{{}}</span>-->
        <!--</el-col>-->
      </el-row>
      <el-row class="line-text">
        <el-col :span="8">
          <span class="content-text">扫描总量: {{ biopsyHistory.scanFileCount }}</span>
        </el-col>
        <el-col :span="8">
          <span class="content-text">自动匹配数量: {{ biopsyHistory.autoMatchCount }}</span>
        </el-col>
        <el-col :span="8">
          <span class="content-text">
            手动匹配数量：{{ biopsyHistory.manualMatchCount }}
          </span>
        </el-col>
      </el-row>
      <el-row class="line-text">
        <el-col :span="8">
          <span class="content-text">
            平均切片大小:
            {{ formatBytes(biopsyHistory.averageFileSize) }}
          </span>
        </el-col>
        <el-col :span="8">
          <span class="content-text">
            最大切片大小:
            {{ formatBytes(biopsyHistory.maxFileSize) }}
          </span>
        </el-col>
        <el-col :span="8">
          <span class="content-text">
            最小切片大小：{{ formatBytes(biopsyHistory.minFileSize) }}
          </span>
        </el-col>
      </el-row>
      <el-row class="line-text">
        <el-col :span="8">
          <span class="content-text">
            总上传时长:
            {{ biopsyHistory.formatUploadCostTime }}
          </span>
        </el-col>
        <el-col :span="8">
          <span class="content-text">
            平均上传时长:
            {{ biopsyHistory.formatAverageUploadTime }}
          </span>
        </el-col>
      </el-row>
      <el-row class="line-text">
        <el-col :span="8">
          <span class="content-text">上传开始: {{ biopsyHistory.uploadStartTime }}</span>
        </el-col>
        <el-col :span="8">
          <span class="content-text">上传结束: {{ biopsyHistory.uploadEndTime }}</span>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="biopsyHistoryDialog.visible = false" size="mini">关闭</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="切片详情" :visible.sync="biopsyDetailDialog.visible" width="40%">
      <el-row style="margin-top: 10px" :gutter="20">
        <el-col :span="14">
          <el-row>
            <el-col :span="12">
              <span>切片编号：{{ biopsyDetail.id }}</span>
            </el-col>
            <el-col :span="12">
              <span>扫描倍率：{{ biopsyDetail.level }}</span>
            </el-col>
            <el-col :span="12">
              <span>切片名称：{{ biopsyDetail.originFilename }}</span>
            </el-col>
            <el-col :span="12">
              <span>扫描时间：{{ biopsyDetail.createTime }}</span>
            </el-col>
          </el-row>
          <el-row style="margin-top: 10px">
            <el-form label-width="85px" label-position="left">
              <el-form-item label="切片描述：">
                <el-input type="textarea" placeholder="请输入扫描切片描述" :autosize="{ minRows: 2, maxRows: 10 }"
                  v-model="biopsyDetail.description" size="mini"></el-input>
              </el-form-item>
            </el-form>
          </el-row>
        </el-col>
        <el-col :span="10">
          <img :src="imageServiceURL + biopsyDetail.previewUrl" class="biopsy-detail-img" alt="切片缩略图" />
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="biopsyDetailDialogSave" type="primary" size="mini">保存</el-button>
        <el-button @click="biopsyDetailDialog.visible = false" size="mini">关闭</el-button>
      </span>
    </el-dialog>
    <el-dialog title="切片用途" :visible.sync="sliceUsesDialogVisible" width="30%">
      <el-row>
        <el-col :span="8">
          <el-select v-model="pBiopsyHistoryPurpose" placeholder="请选择切片用途" clearable class="picker-form" size="mini">
            <el-option v-for="item in sliceUsesList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-select v-model="biopsyHistoryHospital" placeholder="请选择切片所属医院" clearable class="picker-form" size="mini"
            @change="getBranchList">
            <el-option v-for="item in hospitalList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-select v-model="branchName" placeholder="请选择分院" clearable class="picker-form" size="mini">
            <el-option v-for="item in branchCourtsList" :key="item.name" :label="item.name"
              :value="item.name"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sliceUsesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="startUploadValue">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BaseTable from '@templates/components/BaseTable';
import _ from 'lodash';
import * as Uppy from 'uppy';
import 'uppy/dist/uppy.min.css';
import $ from 'jquery';
import { itemsPerPage } from '@/client/libs/util';

const Chinese = require('@uppy/locales/lib/zh_CN');

export default {
  name: 'DiagnosisScanNoUpload',
  components: {
    BaseTable,
  },
  data() {
    return {
      imageServiceURL: process.env.ImageServiceURL, // 图片服务器地址
      biopsyScanUrl: process.env.BiopsyScanUrl, // 自动扫描地址
      uppy: null, // 用于上传的对象
      xmlUppy: null, // 用于xml上传的对象
      scanningStatusInterval: null,
      resData: {
        scanningStatusId: 0,
        biopsyHistoryId: 0,
      },
      isStopingUpload: false,
      isResetingDatabase: false,
      sliceUsesDialogVisible: false,
      pBiopsyHistoryPurpose: '',
      biopsyHistoryHospital: '',
      branchName: '',
      biopsyTable: {
        data: [],
        header: [
          {
            label: '扫描批次',
            prop: 'biopsyHistoryId',
            width: '107',
          },
          {
            label: '上传状态',
            prop: 'uploadStatusName',
            width: '107',
          },
          {
            label: '病理编号',
            prop: 'pathologyId',
            width: '107',
          },
          {
            label: '扫描倍率',
            prop: 'level',
            width: '107',
          },
          {
            label: '描述',
            prop: 'description',
          },
        ],
        operation: [
          {
            label: '详情',
            functionKey: 'biopsyTableDesc',
          },
        ],
        // 分页信息
        pageInfo: {
          size: itemsPerPage.get(),
          page: 1,
          total: 0,
        },
      },

      biopsyHistoryDialog: {
        visible: false,
      },

      biopsyHistory: {
        id: 0,
        userName: '',
        userWorkNumber: '',

        scanFileCount: 0,
        autoMatchCount: 0,
        manualMatchCount: 0,

        averageFileSize: 0,
        maxFileSize: 0,
        minFileSize: 0,

        formatUploadCostTime: '',
        formatAverageUploadTime: '',

        uploadStartTime: '',
        uploadEndTime: '',
      },

      biopsyDetailDialog: {
        visible: false,
      },
      biopsyDetail: {
        id: 0,
        level: '0',
        description: '',
        previewUrl: '',
        originFilename: '',
        createTime: '',
      },
      biopsyState: {
        noUpload: 0,
        uploading: 0,
        uploaded: 0,
        unMatch: 0,
        matched: 0,
      },
      dictRequestMap: [
        {
          code: 'sliceUses',
          arrayKey: 'sliceUsesList',
        },
        {
          code: 'hospitalList',
          arrayKey: 'hospitalList',
        },
      ],
      sliceUsesList: [],
      hospitalList: [],
      branchCourtsList: [],
      uploadValue: '',
    };
  },

  mounted() {
    // this.getBranchCourtsInfo();
    this.uppy = this.__initUppy(
      ['.svs', '.mds', '.ndpi', '.kfb', '.sdpc'],
      '/upload'
    );
    this.xmlUppy = this.__initUppy(['.xml'], '/upload/xml', true);
    this.biopsyTableRequest();
    this.scanningStatusRequest();
    this.biopsyStateRequest();
    this.dictionariesRequest();
    this.scanningStatusInterval = window.setInterval(
      this.scanningStatusRequest,
      5000
    ); // 5s 检查一次
    this.biopsyTableInterval = window.setInterval(
      this.biopsyTableRequest,
      5000
    );
    this.biopsyStateInterval = window.setInterval(
      this.biopsyStateRequest,
      5000
    );
  },
  computed: {
    // 按钮显示配置
    isShowUpload() {
      return true;
    },
    isShowExtraUpload() {
      return true;
    },
    isShowResetDatabase() {
      return true;
    },
    isShowBiopsyHistory() {
      return true;
    },

    scanningStatusId() {
      return this.resData.scanningStatusId;
    },
    biopsyHistoryId() {
      return this.resData.biopsyHistoryId;
    },
    // 等待中
    isWaitUploading() {
      return this.scanningStatusId === 1488;
    },
    // 开始
    isUploading() {
      return this.scanningStatusId === 1489;
    },
    canStartUpload() {
      // return true
      return !this.isUploading;
      // this.isWaitUploading && !this.isStopingUpload
      //   && !this.isResetingDatabase && this.biopsyTable.data.length > 0;
    },
    // 补传
    isExtraUploading() {
      return this.scanningStatusId === 1490;
    },
    canStartExtraUpload() {
      return (
        this.isWaitUploading &&
        !this.isStopingUpload &&
        !this.isResetingDatabase
      );
    },
    // 停止
    canStopUpload() {
      return (
        (this.isUploading || this.isExtraUploading) &&
        !this.isStopingUpload &&
        !this.isResetingDatabase
      );
    },
    // 重置
    canResetDatabase() {
      return (
        this.isWaitUploading &&
        !this.isStopingUpload &&
        !this.isResetingDatabase
      );
    },
    scanPandect() {
      return `未上传：${this.biopsyState.noUpload}
      上传中：${this.biopsyState.uploading}
      已上传：${this.biopsyState.uploaded}
      未匹配：${this.biopsyState.unMatch}
      已匹配：${this.biopsyState.matched}`;
    },
  },
  methods: {
    __initUppy(format, url, isXml = false) {
      const allowFormat = ['.svs', '.mds', '.ndpi', '.kfb'];
      const uppy = Uppy.Core({
        locale: Chinese,
        restrictions: {
          maxFileSize: null,
          maxNumberOfFiles: null,
          minNumberOfFiles: null,
          allowedFileTypes: format,
        },
      });
      uppy.use(Uppy.Dashboard, {
        proudlyDisplayPoweredByUppy: false,
        showProgressDetails: true,
        note: `仅支持 ${JSON.stringify(format)}格式文件`,
      });
      uppy.use(Uppy.XHRUpload, {
        timeout: 200 * 1000,
        endpoint: `${this.biopsyScanUrl}${url}`,
        fieldName: 'file',
        method: 'POST',
        formData: true,
        metaFields: ['biopsyHistoryId'],
      });
      uppy.on('file-added', (file) => {
        uppy.setFileMeta(file.id, {
          biopsyHistoryId: this.resData.biopsyHistoryId,
        });
      });
      uppy.on('upload-progress', (file, progress) => {
        if (
          allowFormat.indexOf(`.${file.extension}`) !== -1 &&
          progress.bytesUploaded === progress.bytesTotal
        ) {
          this.$notify({
            title: '成功',
            message: `${file.name}文件上传成功，后台处理中，请稍后！！！`,
            type: 'success',
          });
        }
      });
      // 下载完成后预览图。标签预览图：labelUrl，图像预览图：previewUrl
      uppy.on('upload-success', (file, response) => {
        if (isXml) {
          const msg = response.body.msg;
          if (response.body.code !== 200) {
            this.$notify({
              title: '错误',
              message: `${msg[0].message}`,
              type: 'error',
              duration: 0,
            });
          }
        } else {
          const labelUrl = this.imageServiceURL + response.body.data.labelUrl;
          $(`[title='${file.name}']`)
            .parent()
            .parent()
            .prev()
            .children('.uppy-DashboardItem-previewInnerWrap')
            .html(
              `${'<img class="uppy-DashboardItem-previewImg" ' + 'alt="'}${file.name
              }" src="${labelUrl}">`
            );
          this.$emit('DiagnosisScanMethed');
        }
      });
      return uppy;
    },
    getBranchList(id) {
      this.branchCourtsList = []
      let mData = this.hospitalList.filter((item) => item.id === id)[0]
      if (mData.firstCode) {
        mData.firstCode.split('、').forEach((item) => {
          this.branchCourtsList.push({ name: item })
        })
      }
    },
    getBranchCourtsInfo() {
      this.$axios({
        method: 'GET',
        url: `/PROXY-Remote/branch`,
      }).then((res) => {
        if (res && res.data.code === 200) {
          this.branchCourtsList = res.data.data;
          this.branchId = this.branchCourtsList[0].id;
        }
      });
    },
    scanningStatusRequest() {
      this.$axios({
        method: 'GET',
        url: '/PROXY-Remote/biopsy-history/current',
      }).then((res) => {
        // 请求成功
        const result = res.data.data;
        if (result) {
          this.resData.scanningStatusId = _.get(result, 'scanningStatusId', 0);
          this.resData.biopsyHistoryId = _.get(result, 'biopsyHistory.id', 0);
        }
      });
    },
    startUploadValue() {
      if (
        this.pBiopsyHistoryPurpose === '' ||
        this.biopsyHistoryHospital === ''
      ) {
        this.$message.warning('请选择......');
      } else {
        if (this.uploadValue === 'autoUpload') {
          this.startUpload();
        } else if (this.uploadValue === 'handUpload') {
          this.startExtraUpload();
        }
        this.sliceUsesDialogVisible = false;
      }
    },
    // 开始
    startUpload() {
      this.sliceUsesDialogVisible = false;
      this.resData.scanningStatusId = 1489;
      let mData = {
        biopsyHistoryPurpose: this.pBiopsyHistoryPurpose,
        biopsyHistoryHospital: this.biopsyHistoryHospital,
        branchName: this.branchName,
        status: 'upload',
      };
      this.$axios({
        method: 'POST',
        url: `/PROXY-Remote/biopsy-history/start`,
        data: mData,
      }).then((res) => {
        if (res.data.code === 200) {
          this.$message.success('开始上传');
        } else {
          this.$message.warning('开始上传失败');
        }
        this.scanningStatusRequest();
      });
    },
    // 补传
    startExtraUpload() {
      this.resData.scanningStatusId = 1489;
      let mData = {
        biopsyHistoryPurpose: this.pBiopsyHistoryPurpose,
        biopsyHistoryHospital: this.biopsyHistoryHospital,
        branchName: this.branchName,
        status: 'extra',
      };
      this.$axios({
        method: 'POST',
        url: `/PROXY-Remote/biopsy-history/start`,
        data: mData,
      }).then((res) => {
        if (res.data.code === 200) {
          this.$message.success('开始补传');
        } else {
          this.$message.warning('补传失败');
        }
        this.scanningStatusRequest();
        this.addFiles();
      });
    },
    showSliceUsesialog(value) {
      this.uploadValue = value;
      this.sliceUsesDialogVisible = true;
    },
    // 获取字典信息
    async dictionariesRequest() {
      await this.dictRequestMap.forEach((map) => {
        this.$axios({
          method: 'GET',
          url: '/PROXY-Remote/dicts/list',
          params: {
            code: map.code,
            page: 0,
            size: 99,
          },
        }).then((res) => {
          if (res && res.data.code === 200) {
            this[map.arrayKey] = _.clone(res.data.data);
            if (map.code === 'sliceUses') {
              this.pBiopsyHistoryPurpose = res.data.data[0].id;
            } else if (map.code === 'hospitalList') {
              this.biopsyHistoryHospital = res.data.data[0].id;
              let mData = res.data.data.filter((item) => item.id === this.biopsyHistoryHospital)[0]
              if (mData.firstCode) {
                mData.firstCode.split('、').forEach((item) => {
                  this.branchCourtsList.push({ name: item })
                })
                console.log(this.branchCourtsList)
                this.branchName = this.branchCourtsList[0].name
              }
            }
          }
        });
      });
    },
    addFiles() {
      if (!this.uppy) {
        return;
      }
      this.uppy.reset();
      const dashboard = this.uppy.getPlugin('Dashboard');
      if (!dashboard.isModalOpen()) {
        dashboard.openModal();
      }
    },
    addXmlFiles() {
      if (!this.xmlUppy) {
        return;
      }
      this.xmlUppy.reset();
      const dashboard = this.xmlUppy.getPlugin('Dashboard');
      if (!dashboard.isModalOpen()) {
        dashboard.openModal();
      }
    },
    // 停止
    stopUpload() {
      this.isStopingUpload = true;
      setTimeout(() => {
        this.isStopingUpload = false;
      }, 3000);
      this.$axios({
        method: 'POST',
        url: '/PROXY-Remote/biopsy-history/end',
      }).then((res) => {
        if (res.data.code === 200) {
          if (res.data.info) {
            this.$message.success(res.data.info);
          } else {
            this.$message.success('已停止');
          }
        } else {
          this.$message.warning('停止失败');
        }
        this.scanningStatusRequest();
      });
    },
    // 重置
    resetDatabase() {
      this.isResetingDatabase = true;
      setTimeout(() => {
        this.isResetingDatabase = false;
      }, 3000);
      this.$axios({
        method: 'DELETE',
        url: '/PROXY-Remote/biopsy/reset',
      }).then((res) => {
        // TODO 重置待完成
        if (res.data.code === 200) {
          this.$message.success('重置成功');
        } else {
          this.$message.warning('重置失败');
        }
        this.scanningStatusRequest();
      });
    },
    // 扫描详情
    biopsyHistoryDialogOpen() {
      this.biopsyHistoryRequest();
      this.biopsyHistoryDialog.visible = true;
      return false;
    },
    async biopsyHistoryRequest() {
      try {
        await this.$axios({
          method: 'GET',
          url: `/PROXY-Remote/biopsy-history/search/${this.resData.biopsyHistoryId}`,
        }).then((res) => {
          // 请求失败
          if (res.data.code !== 200) {
            throw new Error(res.data);
          }

          // 请求成功
          const result = res.data.data;
          // 查询结果数据
          Object.keys(this.biopsyHistory).forEach((key) => {
            if (typeof this.biopsyHistory[key] === 'string') {
              this.biopsyHistory[key] = _.get(result, key, '');
            } else if (typeof this.biopsyHistory[key] === 'number') {
              if (
                _.get(result, key, 0) === null ||
                _.get(result, key, 0) === ''
              ) {
                this.biopsyHistory[key] = 0;
              } else {
                this.biopsyHistory[key] = _.get(result, key, 0);
              }
            }
          });
        });
      } catch (e) {
        // 跳出
      }
    },

    // 切片详情
    biopsyDetailDialogOpen(index) {
      Object.keys(this.biopsyDetail).forEach((key) => {
        this.biopsyDetail[key] = this.biopsyTable.data[index][key];
      });
      this.biopsyDetailDialog.visible = true;
    },
    // 切片详情
    async biopsyDetailDialogSave() {
      try {
        await this.$axios({
          method: 'PUT',
          url: '/PROXY-Remote/biopsy',
          data: this.biopsyDetail,
        }).then((res) => {
          // 请求失败
          if (res.data.code !== 200) {
            throw new Error(res.data);
          }

          // 请求成功
          this.$message.success('保存成功');
          this.biopsyTableRequest();
          this.biopsyDetailDialog.visible = false;
        });
      } catch (e) {
        // 跳出
      }
    },

    // 表格 - 按钮点击
    biopsyTableButtonClick(functionKey, row) {
      this[functionKey](row);
    },
    // 表格 - 切片详情
    biopsyTableDesc(row) {
      this.biopsyDetailDialogOpen(row.index);
    },
    // 分页跳转
    biopsyTablePageJumpTo(val) {
      this.biopsyTable.pageInfo.page = val;
      this.biopsyTableRequest();
    },
    // 每页显示数量改变
    biopsyTableSizeChange(val) {
      this.biopsyTable.pageInfo.size = val;
      this.biopsyTableRequest();
    },

    // 请求切片数据
    async biopsyTableRequest() {
      try {
        await this.$axios({
          method: 'GET',
          url: '/PROXY-Remote/biopsy/list/forNoUploadAndNoMatch',
          params: {
            currentLevel: 1,
            page: this.biopsyTable.pageInfo.page - 1,
            size: this.biopsyTable.pageInfo.size,
          },
        }).then((res) => {
          // 请求失败
          if (res.data.code !== 200) {
            throw new Error(res.data);
          }

          // 请求成功
          const result = res.data;
          // 分页信息
          this.biopsyTable.pageInfo = {
            total: result.pageInfo.total,
            page: result.pageInfo.page + 1,
            size: result.pageInfo.size,
          };
          // 查询结果数据
          this.biopsyTable.data = [];
          result.data.forEach((t, index) => {
            const item = t;
            item.index = index;

            item.uploadStatusName = t.currentLevel === 1 ? '未上传' : '上传中';
            this.biopsyTable.data.push(item);
          });
        });
      } catch (e) {
        // 跳出
      }
    },
    async biopsyStateRequest() {
      try {
        await this.$axios({
          method: 'GET',
          url: '/PROXY-Remote/biopsy/count',
        }).then((res, err) => {
          if (res.data.code !== 200) {
            throw new Error(err);
          }
          res.data.data.forEach((item) => {
            if (_.get(item, 'current_level', 0) === 1) {
              this.biopsyState.noUpload = _.get(item, 'count', 0);
            }
            if (_.get(item, 'current_level', 0) === 2) {
              this.biopsyState.uploading = _.get(item, 'count', 0);
            }
            if (_.get(item, 'current_level', 0) === 3) {
              this.biopsyState.uploaded = _.get(item, 'count', 0);
            }
            if (_.get(item, 'current_level', 0) === 4) {
              this.biopsyState.unMatch = _.get(item, 'count', 0);
            }
            if (_.get(item, 'current_level', 0) === 5) {
              this.biopsyState.matched = _.get(item, 'count', 0);
            }
          });
          this.biopsyState.uploaded =
            Number(this.biopsyState.unMatch) + Number(this.biopsyState.matched);
        });
      } catch (e) {
        throw new Error(e);
      }
    },
    formatBytes(bytes, decimals = 2) {
      if (bytes === 0) return '0 B';

      const k = 1024;
      const dm = decimals < 0 ? 0 : decimals;
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

      const i = Math.floor(Math.log(bytes) / Math.log(k));

      return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
    },
  },
  destroyed() {
    if (this.scanningStatusInterval) {
      clearInterval(this.scanningStatusInterval);
      this.scanningStatusInterval = null;
    }
    if (this.biopsyTableInterval) {
      clearInterval(this.biopsyTableInterval);
      this.scanningStatusInterval = null;
    }
    if (this.biopsyStateInterval) {
      clearInterval(this.biopsyStateInterval);
      this.biopsyStateInterval = null;
    }
    // if (this.uppy.getPlugin('Dashboard').isModalOpen()) {
    //     this.uppy.getPlugin('Dashboard').closeModal();
    // }
    // if (this.xmlUppy.getPlugin('Dashboard').isModalOpen()) {
    //     this.xmlUppy.getPlugin('Dashboard').closeModal();
    // }
  },
};
</script>

<style>
.biopsy-detail-img {
  max-width: 150px;
  max-height: 100px;
}

.uppy-u-reset.uppy-Dashboard-browse {
  color: #00be8b;
}

.uppy-size--md .uppy-DashboardContent-back {
  color: #00be8b;
}

.uppy-size--md .uppy-DashboardContent-addMore {
  color: #00be8b;
}

.uppy-StatusBar.is-waiting .uppy-StatusBar-actionBtn--upload {
  background-color: #00be8b;
}

.uppy-StatusBar-spinner {
  fill: #00be8b !important;
}

.uppy-StatusBar.is-complete .uppy-StatusBar-progress {
  background-color: #00be8b;
}

.uppy-StatusBar-progress {
  background-color: #00be8b !important;
}

.uppy-DashboardItem.is-complete .progress {
  stroke: #00be8b;
  fill: #00be8b;
  opacity: 1;
}

.uppy-DashboardItem-previewInnerWrap img {
  z-index: 1000;
  position: absolute;
}
</style>
